<template>
  <div class="conversation-container">
    <div
        ref="messagesArea"
        class="messages-area"
        :class="{ 'messages-area--center': message.length === 0 }"
    >
      <template v-if="message.length === 0">
        <div class="no-conversation-area">
          <svg-icon icon-class="logo" size="64px"/>
          <div class="welcome-title">欢迎使用 AI 聊天助手！</div>
          <div class="welcome-desc">
            支持 <span class="highlight">MCP 多智能体</span>、<span class="highlight">TOOL 工具调用</span>、<span
              class="highlight">DeepSeek 智能对话</span> 等多种能力。
          </div>
          <div class="welcome-tip">请选择左侧会话或发送消息新建会话，体验强大 AI 助手！</div>
        </div>
      </template>
      <template v-else v-for="(msg, idx) in message" :key="idx">
        <!-- user 消息 -->
        <div v-if="msg.role === 'user'" class="message-row user">
          <el-avatar :size="32" :src="userStore.userInfo.avatar" alt="user" class="avatar user-avatar">
            {{ (userStore.userInfo?.username?.slice(0, 2) || '').toUpperCase() }}
          </el-avatar>
          <div class="message-content-block">
            <div class="message-options">
              <!-- 删除按钮：仅所有消息的最后一条展示 -->
              <el-button
                v-if="idx === lastMsgIdx"
                class="option-btn"
                round size="small"
                :disabled="isAiOutputting"
                @click="handleDelete()"
              >
                <svg-icon icon-class="delete"></svg-icon>
                <span class="option-text">删除</span>
              </el-button>
              <!-- 复制按钮：所有 user 消息都展示 -->
              <el-button class="option-btn" round size="small" @click="handleCopy(msg.content || '')">
                <svg-icon icon-class="copy"></svg-icon>
                <span class="option-text">复制</span>
              </el-button>
              <!-- 重试按钮：仅最后一条用户消息，且未在输出时可用 -->
              <el-button
                v-if="idx === lastUserMsgIdx"
                class="option-btn"
                round size="small"
                @click="handleRetry()"
                :disabled="isAiOutputting"
              >
                <svg-icon icon-class="retry"></svg-icon>
                <span class="option-text">重试</span>
              </el-button>
            </div>
            <div class="message-content">
              <Markdown v-model="msg.content" :mode="'preview'"/>
            </div>
            <div class="message-meta">
              <span class="message-time">{{ msg.sendTime }}</span>
            </div>
          </div>
        </div>
        <!-- ai/assistant 消息 -->
        <div v-else-if="msg.role === 'assistant'" class="message-row ai">
          <svg-icon class="avatar ai-avatar" icon-class="deepseek" size="32px"/>
          <div class="message-content-block">
            <div class="message-options">
              <!-- 复制按钮：所有 ai 消息都展示，最后一条 ai 消息且正在输出时禁用 -->
              <el-button class="option-btn" round size="small" @click="handleCopy(msg.content || '')" :disabled="idx === lastAiMsgIdx && isAiOutputting">
                <svg-icon icon-class="copy"></svg-icon>
                <span class="option-text">复制</span>
              </el-button>
              <!-- 删除按钮：仅所有消息的最后一条展示 -->
              <el-button
                v-if="idx === lastMsgIdx"
                class="option-btn"
                round size="small"
                :disabled="isAiOutputting"
                @click="handleDelete()"
              >
                <svg-icon icon-class="delete"></svg-icon>
                <span class="option-text">删除</span>
              </el-button>
            </div>
            <div class="message-content">
              <Markdown v-model="msg.content" :mode="'preview'"/>
            </div>
            <div class="message-meta">
              <span class="message-time">{{ msg.sendTime }}</span>
            </div>
          </div>
        </div>
        <!-- 其他角色消息 -->
        <div v-else class="message-row other">
          <div class="other-message-wrapper">
            <el-collapse :model-value="otherActiveMap[idx] ? ['open'] : []">
              <el-collapse-item name="open">
                <template #title>
                  <span class="other-role">{{ msg.role }}</span>
                  <span class="message-time">{{ msg.sendTime }}</span>
                </template>
                <div class="message-text">{{ msg.content }}</div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </template>
    </div>
    <!-- 输入框区域 -->
    <div class="input-footer">
      <div class="message-footer-options">
        <div class="message-footer-options__left">
          <el-button round @click="openAiConfigDialog('AI配置')">
            <svg-icon icon-class="message-model" size="18px"></svg-icon>
            {{ currentConversationInfo?.configInfo?.model }}
          </el-button>
          <el-button round @click="openAiToolDialog('AI道具')">
            <svg-icon icon-class="message-tool" size="18px"></svg-icon>
            道具
          </el-button>
          <el-button round @click="openAiMaskDialog('AI面具')">
            <svg-icon icon-class="message-small" size="18px"></svg-icon>
            面具
          </el-button>
        </div>
      </div>
      <div class="textarea-wrapper">
        <el-input
            ref="contentInput"
            v-model="prompt"
            :autosize="{ minRows: 3, maxRows: 6 }"
            class="chat-textarea"
            clearable
            placeholder="请输入你要发送的消息,Enter发送..."
            type="textarea"
            @keydown.enter.exact.prevent="onSend"
        ></el-input>
        <span class="send-icon" @click="onSend">
          <svg-icon icon-class="message-send" size="24px"/>
        </span>
      </div>
    </div>
    <!-- 弹出层   -->

    <!-- Ai 配置 -->
    <config-info-dialog
        v-if="aiConfigDialogVisible"
        v-model:current-conversation-info="currentConversationInfo"
        v-model:visible="aiConfigDialogVisible"
        :close-dialog="closeAiConfigDialog"
        :conversation-id="conversationId"
        :loading="aiConfigLoading"
        :title="aiConfigTitle"
        :device="props.device"
    />
    <!-- Ai 道具 -->
    <tools-info-dialog
        v-if="aiToolDialogVisible"
        v-model:current-conversation-info="currentConversationInfo"
        v-model:visible="aiToolDialogVisible"
        :close-dialog="closeAiToolDialog"
        :conversation-id="conversationId"
        :loading="aiToolLoading"
        :title="aiToolTitle"
        :device="props.device"
    />
    <!-- Ai 面具  -->
    <mask-info-dialog
        v-if="aiMaskDialogVisible"
        v-model:current-conversation-info="currentConversationInfo"
        v-model:visible="aiMaskDialogVisible"
        :close-dialog="closeAiMaskDialog"
        :conversation-id="conversationId"
        :loading="aiMaskLoading"
        :title="aiMaskTitle"
        :device="props.device"
    />
  </div>
</template>

<script lang="ts" setup>
import {UserChatConversationDetailVO, UserChatMessageVO} from "@/api/ai/chat/user-chat/type";
import {useUserStore} from "@/store/modules/user";
import {DeviceEnum} from "@/enums/DeviceEnum";
import {fetchEventSource} from "@microsoft/fetch-event-source";
import {AiChatAPI} from "@/api/ai/chat/deepseek";
import {RequestConstant} from "@/constants/request";
import {EventSourceMessage} from "@microsoft/fetch-event-source/lib/cjs/parse";
import type {DeepSeekChatResponse} from '@/api/ai/chat/deepseek/type';
import {UserChatAPI} from "@/api/ai/chat/user-chat";
import {useDialogManage} from "@/hooks/useDialogManage";

// 用于管理每条 reasoning 消息的展开状态
const otherActiveMap = ref<{ [key: number]: boolean }>({});

defineOptions({
  name: "ChatContainer",
  inheritAttrs: false,
});

// 组件 props & emits
const props = withDefaults(defineProps<{
  conversationId: string;
  message: UserChatMessageVO[];
  currentConversationInfo?: UserChatConversationDetailVO;
  device?: DeviceEnum;
}>(), {
  currentConversationInfo: () => ({}) as UserChatConversationDetailVO,
  device: DeviceEnum.DESKTOP
});

const emits = defineEmits<{
  (event: "update:currentConversationInfo", currentConversationInfo: UserChatConversationDetailVO): void
  (event: "update:message", message: UserChatMessageVO[]): void
  (event: "messageSent", content: string): void
  (event: "loadConversation"): void
  (event: "titleShouldUpdate", conversationId: string): void
}>()

// hooks
const {
  visible: aiConfigDialogVisible,
  title: aiConfigTitle,
  loading: aiConfigLoading,
  openDialog: openAiConfigDialog,
  closeDialog: closeAiConfigDialog,
} = useDialogManage();

const {
  visible: aiMaskDialogVisible,
  title: aiMaskTitle,
  loading: aiMaskLoading,
  openDialog: openAiMaskDialog,
  closeDialog: closeAiMaskDialog,
} = useDialogManage();

const {
  visible: aiToolDialogVisible,
  title: aiToolTitle,
  loading: aiToolLoading,
  openDialog: openAiToolDialog,
  closeDialog: closeAiToolDialog,
} = useDialogManage();
const currentConversationInfo = useVModel(props, 'currentConversationInfo', emits)
const message = useVModel(props, 'message', emits)
const userStore = useUserStore();
// 数据
const avatar = computed(() => userStore.userInfo.avatar)
const messagesArea = ref<HTMLElement | null>(null)
const isUserScrolling = ref(false);
const token = RequestConstant.Header.AuthorizationPrefix + userStore.authInfo.accessToken;
const prompt = ref("")
const sseController = ref<AbortController | null>(null)

// 新增：判断是否为最后一条 user/ai 消息
const lastUserMsgIdx = computed(() => {
  for (let i = message.value.length - 1; i >= 0; i--) {
    if (message.value[i].role === 'user') return i;
  }
  return -1;
});
const lastAiMsgIdx = computed(() => {
  for (let i = message.value.length - 1; i >= 0; i--) {
    if (message.value[i].role === 'assistant') return i;
  }
  return -1;
});
// 新增：判断是否为所有消息的最后一条
const lastMsgIdx = computed(() => message.value.length - 1);
// 新增：判断 ai 是否正在输出（即 sseController 不为 null）
const isAiOutputting = computed(() => !!sseController.value);

onMounted(() => {
  if (messagesArea.value) {
    messagesArea.value.addEventListener('scroll', handleScroll);
  }
});
onBeforeUnmount(() => {
  if (messagesArea.value) {
    messagesArea.value.removeEventListener('scroll', handleScroll);
  }
});

function handleScroll() {
  const el = messagesArea.value;
  if (!el) return;
  // 距离底部小于等于10px，认为用户没有手动滚动
  const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
  isUserScrolling.value = distanceToBottom > 10;
}

/**
 * 删除最后一条消息
 */
async function handleDelete() {
  await AiChatAPI.DELETE_MESSAGE.request(props.conversationId);
  message.value = message.value.slice(0, -1);
}

/**
 * 通用 SSE 聊天流启动方法
 */
function startSSEWithApi({
  messageList,
  conversationId,
  endpoint,
  body
}: {
  messageList: UserChatMessageVO[],
  conversationId: string,
  endpoint: string,
  body: any
}) {
  if (sseController.value) {
    sseController.value.abort();
  }
  sseController.value = new AbortController();
  let aiMsg: UserChatMessageVO = {
    role: 'assistant',
    content: '正在思考中...'
  };
  let aiMsgIndex = messageList.length;
  let reasoningMsgIndex = -1;
  let toolsMsgIndex = -1;
  let aiMsgHasContent = false;
  const msgList = [...messageList, aiMsg];
  message.value = msgList;
  fetchEventSource(endpoint, {
    headers: {
      "Content-Type": "application/json",
      Authorization: token
    },
    method: "POST",
    body: JSON.stringify(body),
    signal: sseController.value.signal,
    openWhenHidden: true,
    onopen: async (response) => {
      if (messageList.length > 0 && messageList.length <= 2) {
        emits('loadConversation');
      }
    },
    onmessage: (ev: EventSourceMessage) => {
      const data: DeepSeekChatResponse = JSON.parse(ev.data);
      const text = data?.result?.output?.text || '';
      const reasoningContent = data?.result?.output?.reasoningContent || '';
      const finishReason = data?.result?.output?.metadata?.finishReason;
      if (reasoningContent) {
        if (reasoningMsgIndex === -1) {
          const reasoningMsg: UserChatMessageVO = {
            role: 'reasoning',
            content: reasoningContent
          };
          msgList.splice(aiMsgIndex, 0, reasoningMsg);
          reasoningMsgIndex = aiMsgIndex;
          aiMsgIndex += 1;
          otherActiveMap.value[reasoningMsgIndex] = true;
        } else {
          msgList[reasoningMsgIndex].content += reasoningContent;
        }
      }
      if (text) {
        if (!aiMsgHasContent) {
          msgList[aiMsgIndex].content = text;
          aiMsgHasContent = true;
        } else {
          msgList[aiMsgIndex].content += text;
        }
      }
      if (finishReason === 'STOP') {
        msgList[aiMsgIndex].sendTime = new Date().toLocaleString();
        if (reasoningMsgIndex !== -1) {
          msgList[reasoningMsgIndex].sendTime = new Date().toLocaleString();
          otherActiveMap.value[reasoningMsgIndex] = false;
        }
        sseController.value?.abort();
        sseController.value = null;
        nextTick(() => {
          emits('titleShouldUpdate', conversationId);
        });
      }
      if (props.conversationId === conversationId) {
        message.value = [...msgList];
      }
    },
    onerror: (err) => {
      console.log("Error:", err);
      sseController.value?.abort();
      sseController.value = null;
    }
  });
}

// 监听 enter 鍵發送
function onSend() {
  if (prompt.value.trim() === "") {
    ElNotification.warning({
      title: "提示",
      message: "消息内容不能为空！",
      duration: 1000
    });
    return;
  }
  if (sseController.value) {
    ElNotification.warning({
      title: "提示",
      message: "请等待Ai响应完成后再发送新消息！",
      duration: 1000
    });
    return;
  }
  const userMsg: UserChatMessageVO = {
    role: 'user',
    content: prompt.value,
    sendTime: new Date().toLocaleString(),
  };
  const newMsgList = [...message.value, userMsg];
  message.value = newMsgList;
  prompt.value = "";
  startSSEWithApi({
    messageList: newMsgList,
    conversationId: props.conversationId,
    endpoint: AiChatAPI.CHAT.endpoint,
    body: {
      conversationId: props.conversationId,
      prompt: userMsg.content
    }
  });
}

/**
 * 重试最后一条用户消息
 */
function handleRetry() {
  // 找到最后一条用户消息索引
  const lastUserIdx = lastUserMsgIdx.value;
  if (lastUserIdx === -1) return;
  // 删除最后一条用户消息及其后的所有消息
  const newMsgList = message.value.slice(0, lastUserIdx + 1);
  message.value = newMsgList;
  // 启动 SSE，endpoint 用 retry，body 可为空
  startSSEWithApi({
    messageList: newMsgList,
    conversationId: props.conversationId,
    endpoint: AiChatAPI.RETRY.endpoint(props.conversationId),
    body: {}
  });
}

watch(message, async () => {
  await nextTick();
  const el = messagesArea.value;
  if (!el) return;
  // 第一条消息直接滚动
  if (message.value.length === 1) {
    el.scrollTop = el.scrollHeight;
    return;
  }
  // 只有未手动滚动时才自动滚动
  if (!isUserScrolling.value) {
    el.scrollTop = el.scrollHeight;
  }
});

// 新增：复制到剪贴板方法
function handleCopy(content: string) {
  if (!content) return;
  navigator.clipboard.writeText(content).then(() => {
    ElNotification.success({
      title: '复制成功',
      message: '内容已复制到剪贴板',
      duration: 1000
    });
  }).catch(() => {
    ElNotification.error({
      title: '复制失败',
      message: '请检查浏览器权限',
      duration: 1000
    });
  });
}
</script>

<style lang="scss" scoped>
.conversation-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  position: relative;
}

.no-conversation-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin: 0 auto 40px auto;
  min-height: 320px;
  padding-bottom: 40px;
  box-sizing: border-box;
  flex: 1;
}

.welcome-title {
  margin-top: 28px;
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  letter-spacing: 1px;
}

.welcome-desc {
  margin-top: 24px;
  font-size: 17px;
  color: #666;
  text-align: center;
  line-height: 1.8;

  .highlight {
    color: #409eff;
    font-weight: 500;
  }
}

.welcome-tip {
  margin-top: 32px;
  font-size: 16px;
  color: #888;
  text-align: center;
  letter-spacing: 0.5px;
}

.messages-area {
  flex: 1 1 auto;
  overflow-y: auto;
  padding: 0;
  width: 86%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; // 聊天内容从顶部开始
}

.messages-area--center {
  justify-content: center; // 欢迎内容居中
}

:deep(.vuepress-markdown-body:not(.custom)) {
  padding: 0;
}

// 暗黑模式兼容
:deep(.vuepress-markdown-body) {
  background-color: inherit;
  color: inherit;
}

:deep(.v-md-editor) {
  background-color: inherit;
  color: inherit;
}

.message-row {
  display: flex;
  align-items: flex-start;
  margin: 8px 0;
  font-size: 15px;
  line-height: 1.7;
  word-break: break-all;

  &.user {
    flex-direction: row-reverse;

    .user-avatar {
      width: 32px !important;
      height: 32px !important;
      border-radius: 50%;
      margin-left: 10px;
      margin-right: 0;
      align-self: flex-start;
      flex-shrink: 0;
    }

    .message-content-block {
      width: 86%;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      margin-right: 10px;
    }

    .message-content {
      width: 100%;
      text-align: right;
      margin-top: 4px;
    }

    .message-meta {
      color: #999;
      font-size: 12px;
      min-width: 90px;
      text-align: right;
      margin-top: 2px;
    }
  }

  &.ai {
    flex-direction: row;
    justify-content: flex-start;

    .ai-avatar {
      margin-right: 10px;
      width: 32px !important;
      height: 32px !important;
      align-self: flex-start;
      flex-shrink: 0;
      font-size: 32px !important;
      min-width: 32px;
      min-height: 32px;
      max-width: 32px;
      max-height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .message-content-block {
      width: 86%;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-left: 10px;
    }

    .message-content {
      width: 100%;
      text-align: left;
      margin-top: 4px;
    }

    .message-meta {
      color: #999;
      font-size: 12px;
      min-width: 90px;
      text-align: left;
      margin-top: 2px;
    }
  }

  &.other {
    justify-content: center;

    .other-message-wrapper {
      width: 80%;
      margin: 0 auto;

      .el-collapse {
        border: none;
        box-shadow: none;
        background: none;
      }

      .el-collapse-item__header {
        font-weight: bold;
        font-size: 15px;
        background: none;
        border: none;
        padding-left: 0;
      }

      .el-collapse-item__wrap {
        background: none;
        border: none;
      }

      .v-md-editor {
        padding: 8px 0;
        font-size: 16px;
      }

      .other-role {
        margin-right: 8px;
        color: #666;
      }

      .message-time {
        color: #999;
        font-size: 12px;
      }
    }
  }
}

.input-footer {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 0 12px 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);
  position: sticky;
  bottom: 0;
  z-index: 2;
}

.message-footer-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 86%;
  margin: 0 auto 8px auto;
  padding: 0 0 0 0;
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */

  .svg-icon {
    cursor: pointer;
  }

  &__left {
    .svg-icon {
      margin-right: 10px;
    }
  }
}

.message-footer-options::-webkit-scrollbar {
  display: none;
}

.textarea-wrapper {
  position: relative;
  width: 86%;
  margin: 0 auto;
}

.chat-textarea {
  width: 100%;
  min-width: 200px;
  display: block;

  :deep(.el-textarea__inner) {
    resize: none;
    overflow-y: auto;
    max-height: 160px;
    min-height: 44px; /* 2行高度 */
    line-height: 1.6;
    font-size: 15px;
    padding-right: 38px; /* 给右侧按钮留空间 */
    border-radius: 16px;
  }
}

.send-icon {
  position: absolute;
  right: 20px;
  bottom: 10px;
  z-index: 3;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  transition: color 0.2s;
  color: #409eff;

  &:hover {
    color: #66b1ff;
  }
}

.option-btn {
  position: relative;

  .option-text {
    display: inline-block;
    opacity: 0;
    max-width: 0;
    margin-left: 4px;
    transition: opacity 0.25s, max-width 0.25s;
    overflow: hidden;
    white-space: nowrap;
    vertical-align: middle;
  }

  &:hover .option-text {
    opacity: 1;
    max-width: 100px;
  }
}

@media (max-width: 768px) {
  .option-text {
    display: none !important;
  }
}
</style>